﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MES.Server.API.Application.Command.Weather;
using MES.Server.API.Dto.Weather;
using ReturnValue;

namespace MES.Server.API.Controllers
{
    /// <summary>
    /// 高德天气控制器
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    // [Authorize] // 暂时注释掉授权要求，用于测试
    public class GaoDeWeatherController : ControllerBase
    {
        private readonly IMediator _mediator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者模式处理器</param>
        public GaoDeWeatherController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 获取高德天气信息
        /// </summary>
        /// <param name="city">城市编码（adcode），必填参数</param>
        /// <param name="extensions">气象类型，可选参数，默认值：all（可选值：base-实况天气，all-预报天气）</param>
        /// <param name="output">返回格式，可选参数，默认值：JSON（可选值：JSON，XML）</param>
        /// <returns>高德天气信息</returns>
        /// <remarks>
        /// 示例请求：
        /// GET /api/GaoDeWeather?city=110100&amp;extensions=all&amp;output=JSON
        /// 
        /// 参数说明：
        /// - city: 城市编码（adcode），必填，如：110100（北京市）
        /// - extensions: 气象类型，可选，base-返回实况天气，all-返回预报天气
        /// - output: 返回格式，可选，JSON或XML，默认JSON
        /// </remarks>
        [HttpGet]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 200)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 400)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 500)]
        public async Task<IActionResult> GetWeather(
            [FromQuery] string city,
            [FromQuery] string extensions = "all",
            [FromQuery] string output = "JSON")
        {
            try
            {
                // 创建查询命令
                var command = new GetGaoDeWeatherCommand
                {
                    City = city,
                    Extensions = extensions,
                    Output = output
                };

                // 执行查询
                var result = await _mediator.Send(command);

                // 根据结果返回相应的HTTP状态码
                if (result.Code ==ReturnValue.StatusCode.Success)
                {
                    return Ok(result);
                }
                else
                {
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                return StatusCode(500, new ApiResult<GaoDeWeatherOutPut>
                {
                    Code = ReturnValue.StatusCode.Fail,
                    Message = $"服务器内部错误：{ex.Message}",
                    Data = null
                });
            }
        }

        /// <summary>
        /// 获取实况天气信息
        /// </summary>
        /// <param name="city">城市编码（adcode），必填参数</param>
        /// <returns>实况天气信息</returns>
        /// <remarks>
        /// 示例请求：
        /// GET /api/GaoDeWeather/live?city=110100
        /// 
        /// 参数说明：
        /// - city: 城市编码（adcode），必填，如：110100（北京市）
        /// </remarks>
        [HttpGet("live")]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 200)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 400)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 500)]
        public async Task<IActionResult> GetLiveWeather([FromQuery] string city)
        {
            try
            {
                // 创建查询命令，获取实况天气
                var command = new GetGaoDeWeatherCommand
                {
                    City = city,
                    Extensions = "base", // 实况天气
                    Output = "JSON"
                };

                // 执行查询
                var result = await _mediator.Send(command);

                // 根据结果返回相应的HTTP状态码
                if (result.Code == ReturnValue.StatusCode.Success)
                {
                    return Ok(result);
                }
                else
                {
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                return StatusCode(500, new ApiResult<GaoDeWeatherOutPut>
                {
                    Code = ReturnValue.StatusCode.Fail,
                    Message = $"服务器内部错误：{ex.Message}",
                    Data = null
                });
            }
        }

        /// <summary>
        /// 获取预报天气信息
        /// </summary>
        /// <param name="city">城市编码（adcode），必填参数</param>
        /// <returns>预报天气信息</returns>
        /// <remarks>
        /// 示例请求：
        /// GET /api/GaoDeWeather/forecast?city=110100
        /// 
        /// 参数说明：
        /// - city: 城市编码（adcode），必填，如：110100（北京市）
        /// </remarks>
        [HttpGet("forecast")]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 200)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 400)]
        [ProducesResponseType(typeof(ApiResult<GaoDeWeatherOutPut>), 500)]
        public async Task<IActionResult> GetForecastWeather([FromQuery] string city)
        {
            try
            {
                // 创建查询命令，获取预报天气
                var command = new GetGaoDeWeatherCommand
                {
                    City = city,
                    Extensions = "all", // 预报天气
                    Output = "JSON"
                };

                // 执行查询
                var result = await _mediator.Send(command);

                // 根据结果返回相应的HTTP状态码
                if (result.Code == ReturnValue.StatusCode.Success)
                {
                    return Ok(result);
                }
                else
                {
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                return StatusCode(500, new ApiResult<GaoDeWeatherOutPut>
                {
                    Code = ReturnValue.StatusCode.Fail,
                    Message = $"服务器内部错误：{ex.Message}",
                    Data = null
                });
            }
        }
    }
}
